import {useRequest} from '@umijs/hooks';
import {Button, Cascader, Form, Input, message, Select, Switch} from 'antd';
import {Store} from 'rc-field-form/lib/interface';
import React, {useEffect, useRef, useState} from 'react';
import {fetchRequest} from '../../../utils/Request';
import {url} from '../../../utils/url';
import {getSecretString} from "@/utils/encrypt";

const {Option} = Select
export default function ModifySchool(props: any) {
    const {content} = props;


    let param = useRef({
        pid: '0',
        selectedOption: []
    })
    const [show, setShow] = useState<boolean>(false)
    /*显示添加密码*/
    const [isAdd, setIsAdd] = useState<boolean>(props.content.haveManager)

    const [active, setActive] = useState<boolean>(props.content.epidemicIsActive)

    const layout = {
        labelCol: {span: 5},
        wrapperCol: {span: 14},
    };

    const tailLayout = {
        wrapperCol: {offset: 5, span: 14},
    };
    const onValuesChange = (changedValues: any) => {
        if ("isSendMsgRecord" in changedValues) {
            setShow(changedValues?.isSendMsgRecord)
        }

        if ("isAdd" in changedValues) {
            setIsAdd(changedValues.isAdd)
        }

        if ("epidemicIsActive" in changedValues) {
            setActive(changedValues.epidemicIsActive)
        }


    }

    const [form] = Form.useForm();


    //添加和修改
    const {loading, data} = useRequest(() => fetchRequest(url.GET_CHOICE_LIST, {}), {

        onSuccess: async (result, params) => {

            if (result.success) {


            } else {
                message.error(result.errorMsg)
            }
        }
    })


    //点击完成的时候
    function handleFinish(value: Store) {
        console.log(value.regionId)
        const params = {
            ...value,
            epidemicIsActive: value.epidemicIsActive ? 1 : 0,
            collegeID: props.content.collegeID,
            isAdd: content.haveManager ? false : isAdd,
            pwd: getSecretString(value.pwd),
            collegeTerm: value.collegeTerm.key,
            regionId: value.regionId.length === 0 ? content.regionId : value.regionId[value.regionId.length - 1],
            regionName: param.current.selectedOption.length === 0 ? content.regionName : param.current.selectedOption.join('/'),
            cityId: param.current.pid
        }
        addInfo.run(params)
    }

    //新增的学校的信息
    async function addInfoRequest(params: Store) {
        try {
            const json = await fetchRequest(url.MODIFY_SCHOOL_INFO, params);

            if (json.success) {
                props.modifySuccess();
            } else {
                message.destroy();
                message.error(json.error);

            }
            return json
        } catch (error: any) {
            message.destroy();
            message.error(error.message);
        }
    }

    const addInfo = useRequest(addInfoRequest, {
        manual: true,
        loadingDelay: 200,
        onSuccess: (result) => {

        }
    })


    const hidden = show ? 'shows' : 'hidden'
    const hides = isAdd ? 'shows' : 'hidden'
    const activeHide = active ? 'shows' : 'hidden'

    const getAllAddress = useRequest((params) => fetchRequest(url.GET_NATIONAL_ADDRESS, params), {
        manual: true,
        loadingDelay: 200,
        onSuccess: (res) => {
            setOptions(res?.data)

        }
    })
    const [options, setOptions] = useState([]);
    const loadData = async (selectedOptions: any) => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        const {data} = await getAllAddress.run({
            id: targetOption.id
        })

        targetOption.loading = false;
        targetOption.children = data


        setOptions([...options]);
    }

    useEffect(() => {


        getAllAddress.run({id: 0})
        setShow(content.isSendMsgRecord === "1")
    }, [])

    const onChange = (value: any, selectedOptions: any) => {
        if (selectedOptions) {
            param.current.selectedOption = selectedOptions.map((item: any) => item.name)
            param.current.pid = (selectedOptions[selectedOptions.length - 1].pid)
        }
    }


    return (
        <Form {...layout} initialValues={{
            // PropManageCom: content.isPropManageCom === "1",
            isSendMsgRecord: content.isSendMsgRecord === "1",
            isFaceNecessary: content.isFaceNecessary === "1",
            isWhiteCardRecord: content.isWhiteCardRecord === "1",
            isSmartStudentCardRecord: content.isSmartStudentCardRecord === "1",
            isBlackCardRecord: content.isBlackCardRecord === "1",
            isShortSendMsgRecord: content.isShortSendMsgRecord === "1",
            isFaceCardRecord: content.isFaceCardRecord === "1",
            collegeName: content.collegeName,
            contact: content.contact,
            contactPhone: content.contactPhone,
            addrDesc: content.addrDesc,
            isAdd: content.haveManager,
            area: content.areaId,
            collegeTerm: {key: content.collegeTermId, label: content.collegeTerm},
            regionName: [content.regionName],
            regionId: [content.regionId],
            college_type: content.collegeType,
            locationCode: content.locationCode,
            epidemicIsActive: content.epidemicIsActive == '1',
            epidemicContactName: content.epidemicContactName,

            epidemicContactPhone: content.epidemicContactPhone
        }} form={form} onFinish={handleFinish} onValuesChange={onValuesChange}>

            <Form.Item name="collegeName" label="学校名称" rules={[{required: true, message: "必须要填写学校名称!"}]}>
                <Input/>
            </Form.Item>

            <Form.Item validateTrigger="onBlur" name="collegeTerm" label="所属学段"

                       rules={[{required: true, message: "必须要选择所属学段!"}]}>
                <Select labelInValue>
                    {data?.data?.collegeTerms?.map((item: any) => <Option
                        value={item.id} key={item.id}>{item.name}</Option>)}
                </Select>
            </Form.Item>
            <Form.Item validateTrigger="onBlur" name="regionId" label="行政区域"
                       rules={[{required: true, message: "必须要选择行政区域!"}]}>
                <Cascader

                    fieldNames={{label: 'name', value: 'id', children: 'children'}}
                    placeholder="必须要选择行政区域"
                    options={options}
                    loadData={loadData}
                    onChange={onChange}
                    displayRender={(label,selectedOptions) => {

                        if (!selectedOptions?.[0]) {
                            return content.regionName;
                        }
                        return label.join('/');
                    }}

                />


            </Form.Item>
            <Form.Item validateTrigger="onBlur" name="area" label="所属教育局"
                       rules={[{required: true, message: "必须要选择所属教育局!"}]}>
                <Select>
                    {data?.data?.educationAreas?.map((item: any) => <Option
                        value={item.id} key={item.id}>{item.educationArea}</Option>)}
                </Select>
            </Form.Item>


            <Form.Item validateTrigger="onBlur" name="college_type" label="办公性质"
                       rules={[{required: true, message: "必须要选择办公性质!"}]}>
                <Select>
                    <Option value={1}>公办</Option>
                    <Option value={2}>民办</Option>
                </Select>
            </Form.Item>


            <Form.Item name="addrDesc" label="学校地址" rules={[{required: true, message: "必须要填写学校地址!"}]}>
                <Input/>
            </Form.Item>

            <Form.Item validateTrigger="onBlur" name="locationCode" label="场所码"

            >
                <Input placeholder="请输入场所码"/>
            </Form.Item>

            {/*<Form.Item name="PropManageCom" label="是否物业" valuePropName="checked" rules={[{ required: true, message: "必须要选择是否物业!" }]}>*/}
            {/*    <Switch />*/}
            {/*</Form.Item>*/}

            <Form.Item name="isAdd" label="是否添加管理员" valuePropName="checked"
            >
                <Switch disabled={content.haveManager} defaultChecked={isAdd}/>
            </Form.Item>


            <Form.Item name="contact" label="管理人姓名" className={hides}>
                <Input disabled={content.haveManager}/>
            </Form.Item>


            <Form.Item validateTrigger="onBlur" name="contactPhone" label="管理人电话" className={hides}
                       rules={[{
                           pattern: /^1[3456789]\d{9}$/,
                           message: '手机号码格式错误！'
                       }]}>
                <Input disabled={content.haveManager}/>
            </Form.Item>

            {!content.haveManager ? <Form.Item name="pwd" label="登录密码" className={hides} rules={[{
                pattern: /^.*(?=.{8,16})(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*?\(\)+=\[\]\{\}_<>,.;:'"-]).*$/,
                message: '密码必须包含数字，字母和特殊字符,至少为8位！'
            }]}>
                <Input.Password/>
            </Form.Item> : null}


            {/*<Form.Item name="isFaceNecessary" label="是否人脸必须" valuePropName="checked"*/}
            {/*>*/}
            {/*    <Switch/>*/}
            {/*</Form.Item>*/}

            <Form.Item name="isSendMsgRecord" label="出入是否发送信息" valuePropName="checked"
            >
                <Switch/>
            </Form.Item>


            <Form.Item name="isWhiteCardRecord" label="白卡" valuePropName="checked"
                       className={`  ${hidden}    `}>
                <Switch/>
            </Form.Item>

            <Form.Item name="isSmartStudentCardRecord" label="智能学生证"
                       className={` ${hidden}    `}
                       valuePropName="checked">
                <Switch/>
            </Form.Item>
            <Form.Item name="isBlackCardRecord" label="黑卡" className={`  ${hidden}    `}
                       valuePropName="checked">
                <Switch/>
            </Form.Item>
            <Form.Item name="isFaceCardRecord" label="人脸" className={`  ${hidden}    `}
                       valuePropName="checked">
                <Switch/>
            </Form.Item>
            <Form.Item name="isShortSendMsgRecord" label="是否发短信" className={`  ${hidden}    `}
                       valuePropName="checked">
                <Switch/>
            </Form.Item>
            <Form.Item name="epidemicIsActive" label="是否添加防疫管理员" valuePropName="checked"
            >
                <Switch/>
            </Form.Item>


            <Form.Item name="epidemicContactName" label="防疫管理人姓名" className={activeHide}>
                <Input placeholder="请输入防疫管理人姓名"/>
            </Form.Item>


            <Form.Item validateTrigger="onBlur" name="epidemicContactPhone" label="防疫管理人电话" className={activeHide}
                       rules={[{
                           pattern: /^1[3456789]\d{9}$/,
                           message: '手机号码格式错误！'
                       }]}>
                <Input placeholder="请输入手机号码"/>
            </Form.Item>


            <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit" loading={addInfo.loading}>提交</Button>
            </Form.Item>

        </Form>
    )
}
